package net.cl.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import javax.servlet.ServletContext;

/**
 * 路径工具类
 * 
 * @author caol64@gmail.com
 */
public class PathUtil {

	/**
	 * 根据给定的文件名寻找资源，从class的根路径开始寻找
	 */
	public static URL getResourceFromRoot(String name) {
		return ClassLoader.getSystemClassLoader().getResource(name);
	}

	/**
	 * 根据给定的文件名寻找资源并读取流，从class的根路径开始寻找
	 */
	public static InputStream getResourceAsStreamFromRoot(String name) throws IOException {
		URL url = getResourceFromRoot(name);
		if (url == null)
			return null;
		return url.openStream();
	}

	/**
	 * 根据给定的文件名寻找资源，从给定的clazz的根路径开始寻找
	 */
	public static URL getResource(Class<?> clazz, String name) {
		return clazz.getResource(name);
	}

	/**
	 * 根据给定的文件名寻找资源并读取流，从给定的clazz的根路径开始寻找
	 */
	public static InputStream getResourceAsStream(Class<?> clazz, String name) throws IOException {
		URL url = getResource(clazz, name);
		if (url == null)
			return null;
		return url.openStream();
	}

	/**
	 * 寻找web项目的资源，从根路径开始寻找
	 */
	public static URL getResource(ServletContext context, String name) {
		try {
			return context.getResource(name);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 寻找web项目的资源并读取流，从根路径开始寻找
	 */
	public static InputStream getResourceAsStream(ServletContext context, String name) throws IOException {
		URL url = getResource(context, name);
		if (url == null)
			return null;
		return url.openStream();
	}

	/**
	 * Adds a file to the classpath.
	 */
	public static void addToClassPath(String path) throws IOException {
		File f = new File(path);
		addToClassPath(f);
	}

	/**
	 * Adds a file to the classpath
	 */
	public static void addToClassPath(File f) throws IOException {
		addToClassPath(f.toURI().toURL());
	}

	/**
	 * Adds the content pointed by the URL to the classpath.
	 */
	public static void addToClassPath(URL u) throws IOException {
		URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		Class<?> sysclass = URLClassLoader.class;
		try {
			Method method = sysclass.getDeclaredMethod("addURL", URL.class);
			method.setAccessible(true);
			method.invoke(sysloader, new Object[] { u });
		} catch (Throwable t) {
			throw new IOException(t);
		}
	}

}
